#方法体中注意要对变量进行校验，方便在进行配置化编程时处理异常

# 参考 https://blog.csdn.net/weixin_55154866/article/details/128098092
# 参考 https://www.runoob.com/python/python-email.html
# 参考 https://blog.csdn.net/YP_FlowerSky/article/details/124451913
import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import pdfplumber
from pathlib import Path

class EmailSender:
    def __init__(self,mail_host,mail_user,mail_pass,sender):
        '''
        @param mail_host 设置登录及服务器信息,比如网易邮箱是smtp.163.com; type=str
        @param mail_user 邮箱用户名; type=str
        @param mail_pass 邮箱授权码; type=str
        @param sender 邮件发送方邮箱地址; type=str
        '''
        self.mail_host = mail_host
        self.mail_user = mail_user
        self.mail_pass = mail_pass
        self.sender = sender

    '''初始化一封邮件'''
    def init_email(self,receivers,content,subject):
        '''
        @param receivers 接收方邮箱集合，适合群发; type=list
        @param content 文本内容；type=str
        @param subject 主题; type=str
        '''
        # 参考 https://blog.csdn.net/YP_FlowerSky/article/details/124451913
        self.receivers = receivers
        # 添加一个MIMEmultipart类，处理正文及附件
        self.message = MIMEMultipart()    #MIMEMultipart可以允许带附件
        self.message['From'] = self.sender  #发送方邮箱地址
        self.message['To'] = ','.join(receivers)   #接收方邮箱地址, 将['1046474088@qq.com','2802428220@qq.com']处理成'1046474088@qq.com,2802428220@qq.com'的str
        self.message['Subject'] = subject
        self.message.attach(MIMEText(content,'plain', 'utf-8')) # 文本内容 (plain文本格式，utf-8编码)

    '''为邮件添加附件'''
    def email_wrapper(self,filePath,fileType="text"):
        '''
        @param filePath 文件路径; type=str
        @param fileType 文件类型，可选 ['text','html','image'];  type=str
        '''
        if(fileType == 'text'):
            suffix = filePath.split(".")[-1]
            # 添加一个pdf文本附件, 用MIMEApplication封装 参考 https://blog.csdn.net/popboy29/article/details/126396549
            if (suffix == 'pdf'):
                with open(filePath, "rb") as f:
                    pdf_attach = MIMEApplication(f.read(), _subtype="pdf")
                    #如果出现邮件发送成功，但邮箱接收到的附件变为bin格式的情况时，检查add_header是否出错 参考https://blog.csdn.net/hxchuadian/article/details/125773738
                    pdf_attach.add_header('Content-Disposition', 'attachment', filename=str(Path(filePath).name))
                    self.message.attach(pdf_attach)
            else:
                #添加一个txt文本附件，用MIMEText封装
                with open(filePath,'r')as h:
                    content2 = h.read()
                #设置txt参数
                text_attach = MIMEText(content2,'plain','utf-8')
                #附件设置内容类型，方便起见，设置为二进制流
                text_attach['Content-Type'] = 'application/octet-stream'
                #设置附件头，添加文件名
                text_attach['Content-Disposition'] = f'attachment;filename="{filePath}"'
                self.message.attach(text_attach)

        if (fileType == 'html'):
            # 推荐使用html格式的正文内容，这样比较灵活，可以附加图片地址，调整格式等
            with open(filePath,'r') as f:
                # 设置html格式参数
                html_attach = MIMEText(f.read(), 'base64', 'gb2312')  # 将html文件以附件的形式发送
                html_attach['Content-Type'] = 'application/octet-stream'
                html_attach.add_header('Content-Disposition', 'attachment',filename=str(Path(filePath).name))  # filename是指下载的附件的命名
                self.message.attach(html_attach)

        if (fileType == 'image'):
            # 添加照片附件，用MIMEImage封装
            with open(filePath, 'rb') as fp:
                picture_attach = MIMEImage(fp.read())
                # 与txt文件设置相似
                picture_attach['Content-Type'] = 'application/octet-stream'
                picture_attach['Content-Disposition'] = f'attachment;filename="{filePath}"'
            # 将内容附加到邮件主体中
            self.message.attach(picture_attach)

    #登录并发送
    def sendEmail(self):
        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(self.mail_host, 25)
            smtpObj.login(self.mail_user, self.mail_pass)
            smtpObj.sendmail(
                self.sender, self.receivers, self.message.as_string())  #receivers群发, receivers是一个列表['1046474088@qq.com','2802428220@qq.com']
            print('success')
            smtpObj.quit()
        except smtplib.SMTPException as e:
            print('error', e)